package ru.acme.lab15.service;

import java.util.LinkedList;
import java.util.Queue;

public class MyBlockingQueue<T> {
	private final Queue<T> queue = new LinkedList<T>();
	
	public MyBlockingQueue() {
	}
	
	public void put(T element) {
		synchronized(queue) {
			queue.add(element);
			queue.notify();
		}
	}

	public T tryTake() {
		synchronized(queue) {
			if (!queue.isEmpty()) {
				T element = queue.remove();
				queue.notify();
				return element;
			}
			return null;
		}
	}
	
	public void waitUntilEmpty() {
		synchronized(queue) {
			while (true) {
				if (queue.isEmpty()) {
					return;
				}
				try {
					queue.wait();
				} catch (InterruptedException e) {
					System.err.println("Unexpected interruption");
					return;
				}
			}
		}
	}
	
}
